package com.fudan.backend.controller;

import com.fudan.backend.exception.RetCode;
import com.fudan.backend.pojo.Category;
import com.fudan.backend.service.CategoryService;
import com.fudan.backend.util.R;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @GetMapping("/category/info/{categoryId}")
    public R getCategoryByCategoryId(@PathVariable("categoryId") String categoryId){
        Category category = categoryService.getCategoryByCategoryId(categoryId);
        return new R(RetCode.CATEGORY_SUCCESS,category);
    }

    @GetMapping("/category")
    public R getAllCategory(int current, int size){
        PageInfo<Category> page = categoryService.getAllCategory(current, size);
        HashMap<String, Object> map = new HashMap<>();
        map.put("categoryPage", page.getList());
        map.put("total", page.getTotal());
        return new R(RetCode.CATEGORY_SUCCESS, map);
    }

    @PostMapping("/category/add")
    public R addCategory(@RequestBody Category category){
        RetCode retCode = categoryService.addCategory(category);
        return new R(retCode);
    }

    @PostMapping("/category/delete/{categoryId}")
    public R deleteCategory(@PathVariable("categoryId") String categoryId){
        RetCode retCode = categoryService.deleteCategory(categoryId);
        return new R(retCode);
    }

    @PostMapping("/category/update")
    public R updateCategory(@RequestBody Category category){
        RetCode retCode = categoryService.updateCategory(category);
        return new R(retCode);
    }

    @GetMapping("/category/search")
    public R getCategoryByPartialCategoryName(String categoryName){
        List<Category> categories = categoryService.getCategoryByPartialCategoryName(categoryName);
        return new R(RetCode.CATEGORY_SUCCESS, categories);
    }
}
